<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    :close-func="closeFunc"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #deptIds="{ model, field }">
        <BasicTree
          v-model:value="model[field]"
          :treeData="treeData"
          :defaultExpandLevel="2"
          :fieldNames="{ title: 'name', key: 'id' }"
          checkable
          toolbar
          title="分配部门"
        />
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form/index';
  import { formSchema } from './data';
  import { BasicTree, TreeItem } from '@/components/Tree';

  import { addRoleApi, updateRoleApi, deptTreeSelectApi, dataScopeApi } from '@/api/system/role';
  import { SUPER_ADMIN_KEY, type SystemRoleItem } from '@/api/system/model/roleModel';

  const isUpdate = ref(true);
  const rowId = ref('');
  const treeData = ref<TreeItem[]>([]);
  const emit = defineEmits(['success', 'register']);

  const [registerForm, { setFieldsValue, resetFields, validate, setProps }] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: formSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    const isAdmin = data.roleKey === SUPER_ADMIN_KEY;
    setProps({ disabled: isAdmin });
    setModalProps({ okButtonProps: { disabled: isAdmin } });
    setModalProps({ confirmLoading: false });
    // 需要在setFieldsValue之前先填充treeData，否则Tree组件可能会报key not exist警告
    if (unref(treeData).length === 0) {
      treeData.value = (await deptTreeSelectApi()) as any as TreeItem[];
    }
    const { id } = data;
    rowId.value = id;
    if (id) {
      const deptData = (await dataScopeApi(id)) as any as TreeItem[];
      setFieldsValue({ ...data, deptIds: deptData });
    }
  });

  const getTitle = computed(() => (!unref(rowId) ? '新增角色' : '编辑角色'));

  const closeFunc = async () => {
    await resetFields();
    return true;
  };

  async function handleSubmit() {
    try {
      const values: SystemRoleItem = await validate();
      setModalProps({ confirmLoading: true });
      unref(rowId) ? await updateRoleApi({ ...values, id: rowId.value }) : await addRoleApi(values);
      closeModal();
      emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
